# -*- coding:utf-8 -*-
import requests
import json
import time
import urllib
from bs4 import BeautifulSoup

session = requests.Session()
headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
            'Origin': 'http://www.v2ex.com',
            'Host': 'www.v2ex.com',
        }

def output_content(res):
    with open('tmp', 'w+') as f:
        f.write(res.content)

def index_get():
    res = session.get('http://www.v2ex.com', headers=headers)
    #output_content(res)
    return res

def login_get():
    res = session.get('http://www.v2ex.com/signin', headers=headers)
    return res

def login_post(once_value):
    payload = { #'u' : urllib.quote('assassinpig@gmail.com'),
                'u' : 'assassinpig@gmail.com',
                'p' : 'xxxxxx',
                'once' : once_value,
                'next' : '/'
              }
    
    res = session.post('http://www.v2ex.com/signin', data=payload, headers=headers)
    print res.status_code
    print res.headers

def daily_get():
    res = session.get('http://www.v2ex.com/mission/daily', headers=headers)
    output_content(res)
    return res

def logout_get(once_value):
    payload = { 'once': once_value}
    res = session.get('http://www.v2ex.com/signout', headers=headers, params=payload)

def parse_once(html_body):
    soup = BeautifulSoup(html_body)
    for input_label in soup.find_all('input'):
        if input_label.get('name') == 'once':
            once_value = input_label.get('value')
            return once_value
    return ''

def parse_logout_once(html_body):
    soup = BeautifulSoup(html_body)
    for input_label in soup.find_all('a'):
        if input_label.get('onclick') != None:
            s = input_label.get('onclick')
            t1 = s.find('once=') + len('once=')
            t2 = s.rfind('\'')
            once_value = s[t1:t2] 
            return once_value
    return ''

res = login_get()
once_value = parse_once(res.content)
#print once_value
login_post(once_value)

#res = index_get()

res = daily_get()
once_value = parse_logout_once(res.content)
#print once_value
logout_get(once_value)
